package com.suneast.suneaststore.modules.goodsdetail.subfragment;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.WebView;

import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.goodsdetail.GoodsHandler;
import com.suneast.suneaststore.modules.goodsdetail.event.BottomPageChangeEvent;
import com.suneast.suneaststore.modules.goodsdetail.event.SubCateLoaded;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.util.net.RestClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;

public class GoodsIntroFragment extends BaseFragment {
    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_goods_intro;
    }

    @BindView(R.id.wv_goods_intro)
    WebView goodsIntroWebView;

    private boolean shouldScroll = false;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        goodsIntroWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        Bundle bundle = getArguments();
        if (bundle != null) {
            int id = bundle.getInt("id");
            shouldScroll = bundle.getBoolean("scroll", false);
            GoodsHandler.requestGoodsIntro(id);
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPageChange(BottomPageChangeEvent event) {
        if (event.getIndex() == 0) {
            if (event.getResponse() != null) {
                JSONObject rootJObj = JSONObject.parseObject(event.getResponse());
                if (rootJObj.getIntValue("code") == 1) {
                    JSONObject dataJObj = rootJObj.getJSONObject("data");
                    if (dataJObj != null) {
                        String webContent = dataJObj.getString("content");
                        goodsIntroWebView.loadData(webContent, "text/html;charset=UTF-8", null);

                        if (shouldScroll) {
                            EventBus.getDefault().post(new SubCateLoaded());
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
